package com.xtt._01_java8;

import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;

/**
 * @Author xtt.
 * @Description: java8 Base64编码
 * @Date:Create in 2017/9/21 0021 下午 21:21
 * @Modify By:
 */
public class Base64Test {

    @Test
    public void test() {
        //Basic编码：是标准的BASE64编码，用于处理常规的需求
        String str = "java8 Base64编码";
        //编码
        String s = Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8));
        System.out.println(s);//amF2YTggQmFzZTY057yW56CB
        //解码
        String s1 = new String(Base64.getDecoder().decode(s.getBytes(StandardCharsets.UTF_8)));
        System.out.println(s1);//java8 Base64编码

        //URL编码：使用下划线替换URL里面的反斜线“/”
        String url = "http://www.importnew.com/14961.html?test=123";
        String s2 = Base64.getUrlEncoder().encodeToString(url.getBytes(StandardCharsets.UTF_8));
        System.out.println(s2);//aHR0cDovL3d3dy5pbXBvcnRuZXcuY29tLzE0OTYxLmh0bWw_dGVzdD0xMjM=

        //MIME编码：使用基本的字母数字产生BASE64输出，而且对MIME格式友好：每一行输出不超过76个字符，而且每行以“\r\n”符结束
        StringBuilder sb = new StringBuilder();
        for (int t = 0; t < 10; ++t) {
            sb.append(UUID.randomUUID().toString());
        }
        byte[] toEncode = sb.toString().getBytes(StandardCharsets.UTF_8);
        String mimeEncoded = Base64.getMimeEncoder().encodeToString(toEncode);
        System.out.println(mimeEncoded);

    }
}
